package com.haoxin.ai_course.modules.course.controller.admin;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.haoxin.ai_course.common.annotation.SysLog;
import com.haoxin.ai_course.common.base.AbstractController;
import com.haoxin.ai_course.common.exception.RRException;
import com.haoxin.ai_course.common.utils.MD5Util;
import com.haoxin.ai_course.common.utils.R;
import com.haoxin.ai_course.modules.course.biz.AcArticleBusiness;
import com.haoxin.ai_course.modules.course.entity.AcArticle;
import com.haoxin.ai_course.modules.course.entity.FileData;
import com.haoxin.ai_course.modules.course.service.AcArticleService;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;



/**
 * 文章表
 * 
 * @author xingxiangguo
 * @email bugcn@qq.com
 * @date 2022-06-06 09:44:48
 */
@RestController
@RequestMapping("/course/acarticle")
@Api(value="api",tags="后台-文章管理")
@Slf4j
public class AdminAcArticleController  extends AbstractController {
	@Autowired
	AcArticleBusiness acArticleBusiness;
	
	@Autowired
	AcArticleService acArticleService;
	
	@Value("${spring.article.UploadUrl}")
	String articleUploadUrl;
	@Value("${spring.article.filePath}")
	String filePath;
	
    /**
     * 列表
     */
    @GetMapping("/list")
    @ApiOperation("文章列表")
//    @RequiresPermissions("course:acarticle:list")
    public R list(@RequestParam Map<String, Object> params){
        //查询列表数据
        QueryWrapper<AcArticle> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().orderByDesc(AcArticle::getId);
        IPage<AcArticle> sysConfigList = acArticleService.page(mpPageConvert.<AcArticle>pageParamConvert(params),queryWrapper);
        return R.ok().put("page", mpPageConvert.pageValueConvert(sysConfigList));
    }


    /**
     * 信息
     */
    @GetMapping("/info/{id}")
    @ApiOperation("根据id查询文章")
//    @RequiresPermissions("course:acarticle:info")
    public R info(@PathVariable("id") Integer id){
        return R.ok().put("acArticle", acArticleService.getById(id));
    }


    /**
     * 新增文章表
     */
    @SysLog("新增文章表数据")
    @PostMapping("/save")
//    @ApiOperation("添加文章")
//    @RequiresPermissions("course:acarticle:save")
    public R save(@RequestBody AcArticle acArticle){
//    	处理content
        acArticleService.save(acArticle);
        return R.ok();
    }
   

    /**
     * 修改
     */
    @SysLog("修改文章表数据")
    @PostMapping("/update")
    @ApiOperation("编辑文章")
//    @RequiresPermissions("course:acarticle:update")
    public R update(@RequestBody AcArticle acArticle){
		acArticleService.updateById(acArticle);
        return R.ok();
    }


    /**
     * 删除
     */
    @SysLog("删除文章表数据")
    @PostMapping("/delete")
    @ApiOperation("删除文章")
    public R delete(@RequestBody Integer[] ids){
		acArticleService.removeByIds(Arrays.asList(ids));
        return R.ok();
    }
    
    /**
	 * 上传文件
	 */
	@RequestMapping("/uploadVideo")
//	@RequiresPermissions("sys:oss:all")
	 @ApiOperation("上传视频")
	public R uploadVideo(@RequestParam("file") MultipartFile file) throws Exception {
		if (file.isEmpty()) {
			throw new RRException("上传视频不能为空");
		}
		String fileId= MD5Util.md5HashCode(file.getInputStream());
		String fileName = file.getOriginalFilename();
//		 String url = articleUploadUrl+"https://ai-class-pro.oss-cn-beijing.aliyuncs.com/";
		 String url = articleUploadUrl+"assets/"+fileName;
		 log.info("异步调用开始");
		 String dateStr = DateUtil.format(new Date(), DatePattern.PURE_DATETIME_PATTERN);
		 String fullFilePath = filePath+dateStr+"/"+fileName;
		 File file2 = new File(filePath+dateStr+"/");
		 if(!file2.exists()) {
			 file2.mkdirs();
		 }
		 File file1 = new File(fullFilePath);
		 file.transferTo(file1);
		 acArticleBusiness.uploadVideo(fileName, fileId, fullFilePath);
		log.info("异步调用执行完毕");
		if(fileName.endsWith("mp4")) {
			R r = new R();
			FileData fileData = new FileData();
			fileData.setUrl(url);
			fileData.setAlt(fileName);
			fileData.setHref(url);
			fileData.setFileId(fileId);
			r.put("data", fileData);
			r.put("errno", 0);
			return r;
		}else {
			List<FileData> jsonArray = new ArrayList<FileData>();
			FileData fileData = new FileData();
			fileData.setUrl(url);
			fileData.setAlt(fileName);
			fileData.setHref(url);
			jsonArray.add(fileData);
			R r = new R();
			r.put("data", jsonArray);
			r.put("errno", 0);
			return r;
		}
	}
	/**
	 * 上传文件
	 */
	@RequestMapping("/uploadImage")
//	@RequiresPermissions("sys:oss:all")
	@ApiOperation("上传图片")
	public R uploadImage(@RequestParam("file") MultipartFile file) throws Exception {
		if (file.isEmpty()) {
			throw new RRException("上传图片不能为空");
		}
		String fileId= MD5Util.md5HashCode(file.getInputStream());
		String fileName = file.getOriginalFilename();
		String url = "https://ai-class-pro.oss-cn-beijing.aliyuncs.com/assets/"+fileName;
		log.info("异步调用开始");
		acArticleBusiness.uploadImage(file.getInputStream(), fileName, fileId);
		log.info("异步调用执行完毕");
//		File file1 = new File("/home/ai_course/filePath/"+fileName);
//		if(!file1.exists()) {
//			file.transferTo(file1);
//		}
//		String url = "http://www.hryrxr.cn/filepath/"+fileName;
		if(fileName.endsWith("mp4")) {
			R r = new R();
			FileData fileData = new FileData();
			fileData.setUrl(url);
			fileData.setAlt(fileName);
			fileData.setHref(url);
			fileData.setFileId(fileId);
			r.put("data", fileData);
			r.put("errno", 0);
			return r;
		}else {
			List<FileData> jsonArray = new ArrayList<FileData>();
			FileData fileData = new FileData();
			fileData.setUrl(url);
			fileData.setAlt(fileName);
			fileData.setHref(url);
			jsonArray.add(fileData);
			R r = new R();
			r.put("data", jsonArray);
			r.put("errno", 0);
			return r;
		}
		
		
	}
	/**
	 * 上传文件
	 */
	@RequestMapping("/uploadToAli")
//	@RequiresPermissions("sys:oss:all")
	@ApiOperation("上传文件")
	public R uploadToAli(@RequestParam("file") MultipartFile file) throws Exception {
		
		if (file.isEmpty()) {
			throw new RRException("上传文件不能为空");
		}
		String fileName = file.getOriginalFilename();
//		String url=AliOssUtil.uploadFileToAli(file.getInputStream(), fileName);
		
		File file1 = new File("/home/ai_course/filePath/"+fileName);
		if(!file1.exists()) {
			file.transferTo(file1);
		}
		String url = "http://www.hryrxr.cn/filepath/"+fileName;
		if(fileName.endsWith("mp4")) {
			R r = new R();
			FileData fileData = new FileData();
			fileData.setUrl(url);
			fileData.setAlt(fileName);
			fileData.setHref(url);
			r.put("data", fileData);
			r.put("errno", 0);
			return r;
		}else {
			List<FileData> jsonArray = new ArrayList<FileData>();
			
			FileData fileData = new FileData();
			fileData.setUrl(url);
			fileData.setAlt(fileName);
			fileData.setHref(url);
			jsonArray.add(fileData);
			R r = new R();
			r.put("data", jsonArray);
			r.put("errno", 0);
			return r;
		}
		
		
	}
	
}
